package com.travelsmart.client.apresentacao.widget;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.travelsmart.client.apresentacao.image.ImagesResource;

public abstract class FormWidget<T> extends Composite{
	protected final HorizontalPanel panel = new HorizontalPanel();
	protected final Image suc = new Image(ImagesResource.INSTANCE.sucesso());
	protected final Image fal = new Image(ImagesResource.INSTANCE.falha());
	protected HandlerValidation<T> handler; 
	
	
	public FormWidget(HandlerValidation<T> handler){
		this.handler = handler;
	}
	
	protected void initHelp(String infoHelp){
		if(infoHelp != null){
		    final DecoratedPopupPanel helpPopup = new DecoratedPopupPanel(true);
		    helpPopup.ensureDebugId("cwBasicPopup-simplePopup");
		    helpPopup.setWidth("150px");
		    helpPopup.setWidget(new HTML(infoHelp));
		    Image help = new Image(ImagesResource.INSTANCE.help());
		    help.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					Widget source = (Widget) event.getSource();
		            int left = source.getAbsoluteLeft() + 10;
		            int top = source.getAbsoluteTop() + 10;
		            helpPopup.setPopupPosition(left, top);
		            helpPopup.show();
				}
			});
		    panel.add(help);	    	
	    }
		suc.setVisible(false);
		fal.setVisible(false);
		panel.add(fal);
		panel.add(suc);
		
	}
	
	public abstract T getValue();
	public abstract void setFocus(boolean focus);
	
	public boolean validar(){
		boolean retorno = true; 
		if(handler != null){
			retorno = handler.handle(getValue());
			if(retorno){
				suc.setVisible(true);
				fal.setVisible(false);
			}else{
				suc.setVisible(false);
				fal.setVisible(true);
				setFocus(true);
			}
		}else{
			clean();
		}
		return retorno;
	}
	public void clean(){
		suc.setVisible(false);
		fal.setVisible(false);
	}
	
	public static interface HandlerValidation<T>{
		public boolean handle(T valor);
	}
	
	

}
